import { useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { useNavigate } from 'react-router-dom'
import CountrySelector from '../components/CountrySelector.jsx'
import CitySelector from '../components/CitySelector.jsx'
import BooleanSelector from '../components/BooleanSelector.jsx'
import formBg from "../assets/formBg.png";
import formBg1 from "../assets/formBg1.png";
import formBg2 from "../assets/formBg2.png";
import { Form, Field, Cell, Button,  Input  } from 'react-vant'
import { Toast } from 'antd-mobile'
import { submitUserInfo } from '../api/index.js'

import { ChinaCity } from '../components/pc.js'

const phoneRegex = /^\d{1,}$/
const numberRegex = /^[0-1]$/

const schema = z.object({
  name: z.string().min(1, '请输入姓名'),
  phone: z.string().regex(phoneRegex, '请输入有效手机号'),
  company: z.string().min(1, '请输入公司名称'),
  country: z.tuple([z.string().min(1, '请选择地区')]),
  city: z.tuple([z.string().min(1, '请选择'), z.string().min(0, '请选择')]),
  // 修改existingCustomer校验，应该匹配BooleanSelector返回的值("0"或"1")
  existingCustomer: z.string().regex(numberRegex, '请选择是否为UPM现有客户'),
  other: z.string().optional(),
})

export default function LeadForm() {
  const navigate = useNavigate()
  const [country, setCountry] = useState([''])
  const [city, setCity] = useState(['', ''])
  const [cityList, setCityList] = useState([])
  // 修改初始状态为字符串而不是数组
  const [existingCustomer, setExistingCustomer] = useState('')
  // 添加loading状态
  const [loading, setLoading] = useState(false)

  // 创建动态schema，根据cityList是否为空来决定city字段是否为必填
  const dynamicSchema = useMemo(() => {
    return schema.extend({
      city: cityList.length 
        ? z.tuple([z.string().min(1, '请选择'), z.string().min(0, '请选择')]) 
        : z.tuple([z.string(), z.string()])
    });
  }, [cityList]);

  const { register, handleSubmit, formState: { errors }, setValue, control } = useForm({
    resolver: zodResolver(dynamicSchema),
    defaultValues: {
      name: '',
      phone: '',
      company: '',
      existingCustomer: '',
      other: '',
      country: [''],
      city: ['', ''],
    }
  })

  const onSubmit = async (data) => {
    // 调用submitUserInfo接口提交数据
    try {
      if(loading) return;
      setLoading(true) // 开始加载
      await submitUserInfo({
        name: data.name,
        phone: data.phone,
        companyName: data.company,
        country: `${data.country[0]}`,
        city: `${[data.city[0], data.city[1]].filter(i => i).join('-')}`,
        isUpmCustomer: parseInt(data.existingCustomer), // 转换为数字
        otherQuestions: data.other || '' // 处理可选字段
      });
      
      Toast.show({
        content: '保存成功',
      })
      setTimeout(() => {
        navigate('/success')
        setLoading(false) // 结束加载
    }, 1000)
    } catch (error) {
      Toast.show({
        content: '提交失败，请重试',
      })
      console.error('提交失败:', error)
      setLoading(false) // 结束加载
    } finally {
    }
  }

  return (
    <form className="w-full h-[100vh] flex flex-col gap-3" 
    layout='vertical' onSubmit={handleSubmit(onSubmit)}>
      <div className="w-full relative">
        <img
          src={formBg}
          alt="隐私政策"
          className="w-[100vw] h-[239px] object-contain mt-[40px]"
        />
        <img
          src={formBg2}
          alt="隐私政策"
          className="w-[96px] h-[89px] object-contain absolute top-[23px] left-[26px]"
        />
        <img
          src={formBg1}
          alt="隐私政策"
          className="w-[30px] h-[38px] object-contain absolute top-[14px] right-[18px]"
        />
      </div>
      <div className="mx-[13px] pt-[23px] px-[14px] pb-[60px] bg-[#FFFFFF]" style={{
        top: '327px',
        left: '13px',
        transform: 'rotate(0deg)',
        opacity: 1,
        gap: '27px',
        borderRadius: '20px',
        paddingTop: '23px',
        paddingBottom: '23px',
        boxShadow: '2px -1px 20.5px 0px #00834240'
      }} >
        <Cell.Group>
          <Field
            className='!p-[0px] !border-none'
            errorMessage={errors.name?.message}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]"><span className="text-[#FF616D] mr-[4px]">*</span>姓名</div>
              <input className="border border-[#CECECE] rounded-[8px] p-[12px] text-[14px] w-[92%]" type="text" placeholder="请输入姓名" {...register('name')} />
            </div>
          </Field>
          
          <Field
            className='!p-[0px] !border-none mt-[14px]'
            errorMessage={errors.phone?.message}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]"><span className="text-[#FF616D] mr-[4px]">*</span>电话</div>
              <input className="border border-[#CECECE] rounded-[8px] p-[12px] text-[14px] w-[92%]" type="tel" inputMode="numeric" placeholder="请输入手机号" {...register('phone')} />
            </div>
            </Field>
          
          <Field
            className='!p-[0px] !border-none mt-[14px]'
            errorMessage={errors.company?.message}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]"><span className="text-[#FF616D] mr-[4px]">*</span>公司名称</div>
              <input className="border border-[#CECECE] rounded-[8px] p-[12px] text-[14px] w-[92%]" type="text" placeholder="请输入公司名称" {...register('company')} />
            </div>
            </Field>
          
          <Field
            className='!p-[0px] !border-none mt-[14px]'
            errorMessage={errors.country?.[0]?.message}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]"><span className="text-[#FF616D] mr-[4px]">*</span>地区选择</div>
              <CountrySelector 
                value={country} 
                onChange={(values, content) => {
                  console.log('values', values, content, content?.value);
                  
                  setCountry(values);
                  setValue('country', values);

                  setCity(['', '']);
                  setValue('city', ['', '']);
                  setCityList(content?.value === '1' ? ChinaCity : []);
                }} 
              />
            </div>
          </Field>
          
          {!!cityList.length && <Field
            className='!p-[0px] !border-none mt-[14px]'
            errorMessage={cityList.length ? (errors.city?.[0]?.message || errors.city?.[1]?.message) : true}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]">
              {!!cityList.length && <span className="text-[#FF616D] mr-[4px]">*</span>}
                城市</div>
              
              <CitySelector 
                value={city}
                list={cityList}
                onChange={(values) => {
                  console.log('values', values);
                  
                  setCity([values[0], values[1]]);
                  setValue('city', [values[0], values[1]]);
                }} 
              />
            </div>
          </Field>}
          
          <Field
            className='!p-[0px] !border-none mt-[14px]'
            errorMessage={errors.existingCustomer?.message}
          >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]"><span className="text-[#FF616D] mr-[4px]">*</span>是否为UPM现有客户</div>
              
              <BooleanSelector 
                value={[existingCustomer, '']} 
                onChange={(values) => {
                  setExistingCustomer(values[0]);
                  setValue('existingCustomer', values[0]);
                }} 
              />
            </div>
          </Field>
          
          <Field
            className='!p-[0px] !border-none mt-[14px]'
            >
            <div className='w-full'>
              <div className="text-sm mb-[7px] text-[#616161]">其他问题</div>
              <textarea className="border border-[#CECECE] rounded-[8px] p-[12px] text-[14px] w-[92%]" rows={3} placeholder="可选填" {...register('other')} />
            </div>
            </Field>
        </Cell.Group>
        
        <div className="mt-[24px] mt-[14px]">
          <Button 
            className='!bg-[#3C8149] !border-[#3C8149]'
            type="primary" 
            round 
            block 
            nativeType="submit"
            loading={loading} // 添加loading状态
            disabled={loading} // 在加载时禁用按钮
          >
            {loading ? '提交中...' : '提交'}
          </Button>
        </div>
      </div>
    </form>
  )
}